/*
 * Copyright (c) 2023, 2023,yzc.cn All rights reserved.
 *
 */
package cn.yzc.controller;

import cn.yzc.ex.ValidateException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Project: SpringMVCPro - BaseController</p>
 * <p>Powered by yzc On 2023-11-02 14:06:01</p>
 * <p>描述：<p>
 *
 * @author yzc [yzc0415@126.com]
 * @version 1.0
 * @since 17
 */
public class BaseController {

   void validator(BindingResult result){
       //读取验证失败的错误列表
        List<FieldError>  fieldErrorList = result.getFieldErrors();
        if (fieldErrorList.size()>0){
            //说明有异常，用map记录错误信息
          Map errors = new HashMap<>();
          //遍历集合
          fieldErrorList.forEach(f->{
              errors.put(f.getField(),f.getDefaultMessage());
          });
          //存在异常信息 抛出异常 中止程序运行
            throw  new ValidateException(errors);
        }

    }
}
